package com.github.zy.rpc.proxy;

import com.github.zy.rpc.client.ClientChannelHolder;
import com.github.zy.rpc.common.protocol.DefaultMessagePacket;
import com.github.zy.rpc.common.protocol.MessagePacketBuilder;
import com.github.zy.rpc.common.protocol.ResponseCode;
import com.github.zy.rpc.domain.MessageResponseModule;
import com.github.zy.rpc.sync.SyncFuture;
import com.github.zy.rpc.sync.SyncFutureHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @version 1.0 created by zy on 2020/4/26 10:15
 */
@Slf4j
@Component
public class RpcRequestClientExecute {


    public String ex(RpcRequestTemplate template) {
        DefaultMessagePacket messagePacket = MessagePacketBuilder.buildBasicRequest()
                .payload(template.getPayload()).moduleId(template.getModuleId()).urlMapping(template.getUrlMapping()).build();
        try {
            //客户端请求服务端
            ClientChannelHolder.CHANNEL_REFERENCE.get().writeAndFlush(messagePacket);
            //完成后，在这里进行一个同步等待，等到客户端接收到数据后，解除后获取数据
            SyncFuture<MessageResponseModule> syncFuture = new SyncFuture();
            SyncFutureHolder.SYNC_FUTURE_MAP.put(messagePacket.getSerialNumber(), syncFuture);

            //todo 这个时间修改为可配置的
            MessageResponseModule responseModule = syncFuture.get(60, TimeUnit.SECONDS);
            if (ResponseCode.SUCCESS.getCode() == responseModule.getCode()) {
                return responseModule.getPayload();
            }
            throw new RuntimeException(String.format("请求发生错误, code: %s , info : %s", responseModule.getCode(), responseModule.getInfo()));
        } finally {
            SyncFutureHolder.SYNC_FUTURE_MAP.remove(messagePacket.getSerialNumber());
        }

    }
}
